package com.pureut.system.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.pureut.common.core.utils.StringUtils;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.domain.*;
import com.pureut.system.domain.dto.MaterialAwmateriaDto;
import com.pureut.system.domain.dto.MaterialBomDetailDto;
import com.pureut.system.domain.dto.MaterialBomDto;
import com.pureut.system.domain.dto.MaterialHalfDto;
import com.pureut.system.domain.vo.MaterialAccessoriesVo;
import com.pureut.system.domain.vo.MaterialBomVo;
import com.pureut.system.domain.vo.MaterialHalfVo;
import com.pureut.system.mapper.*;
import com.pureut.system.service.IMaterialBomService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description bom信息实现类
 * @Param
 * @Date 22-12-02
 * @Author hl
 **/
@Service
public class MaterialBomServiceImpl implements IMaterialBomService {
    @Resource
    private MaterialBomMapper materialBomMapper;

    @Resource
    private MaterialHalfMapper materialHalfMapper;

    @Resource
    private MaterialFinishedMapper materialFinishedMapper;

    @Resource
    private MaterialBomDetailMapper materialBomDetailMapper;

    @Resource
    private MaterialAwmateriaMapper materialAwmateriaMapper;

    @Resource
    private MaterialAccessoriesMapper materialAccessoriesMapper;

    @Resource
    private MaterialBomBehalfMapper materialBomBehalfMapper;

    @Resource
    private SysMidSplitServiceImpl sysMidSplitServiceImpl;


    /**
     * 查询BOM信息
     *
     * @param materialBomVo bom信息接受类
     * @return bom信息集合
     */
    @Override
    @DataScope(deptAlias = "material_bom")
    public List<MaterialBomDto> selectBomList(MaterialBomVo materialBomVo) {
        long haId = 0;
        //如果是半成品
        if(!StringUtils.isEmpty(materialBomVo.getMaterialCode())){
            MaterialHalf materialHalf = new MaterialHalf();
            materialHalf.setMaterialCode(materialBomVo.getMaterialCode());
            materialHalf = materialHalfMapper.selectHalfByList(materialHalf);
            if(materialHalf!=null){
                haId =materialHalf.getMaterialId();
            }
            if(haId>0){
                //半成品是3
                materialBomVo.setBomType(3);
            }else{
                MaterialFinished materialFinished = new MaterialFinished();
                materialFinished.setMaterialCode(materialBomVo.getMaterialCode());
                materialFinished = materialFinishedMapper.selectFinishedByList(materialFinished);
                haId = materialFinished.getMaterialId();
                if(haId>0){
                    //成品是1
                    materialBomVo.setBomType(4);
                }
            }

        }else if(!StringUtils.isEmpty(materialBomVo.getMaterialName())){
            MaterialHalf materialHalf = new MaterialHalf();
            materialHalf.setMaterialName(materialBomVo.getMaterialName());
            materialHalf = materialHalfMapper.selectHalfByList(materialHalf);
            if(materialHalf!=null){
                haId =materialHalf.getMaterialId();
            }
            if(haId>0){
                //半成品是2
                materialBomVo.setBomType(3);
            }else{
                MaterialFinished materialFinished = new MaterialFinished();
                materialFinished.setMaterialName(materialBomVo.getMaterialName());
                materialFinished = materialFinishedMapper.selectFinishedByList(materialFinished);
                haId = materialFinished.getMaterialId();
                if(haId>0){
                    //成品是1
                    materialBomVo.setBomType(4);
                }
            }
        }
        materialBomVo.setMaterialId(haId);
        List<MaterialBomDto> list = materialBomMapper.selectlBomList(materialBomVo);
        for (MaterialBomDto vo:
        list) {
            long ty = vo.getBomType();
            if(ty==4){
                MaterialFinished materialFinished = new MaterialFinished();
                materialFinished.setMaterialId(vo.getMaterialId());
                materialFinished= materialFinishedMapper.selectFinishedByList(materialFinished);
                vo.setMaterialCode(materialFinished.getMaterialCode());
                vo.setMaterialType(materialFinished.getMaterialType());
                vo.setMaterialName(materialFinished.getMaterialName());
                vo.setMaterialSpec(materialFinished.getMaterialSpec());
                vo.setMaterialRatio(materialFinished.getMaterialRatio());
                vo.setMaterialTypeName(materialFinished.getMaterialTypeName());

            }else if(ty==3){
                MaterialHalf materialHalf = new MaterialHalf();
                materialHalf.setMaterialId(vo.getMaterialId());
                materialHalf=materialHalfMapper.selectHalfByList(materialHalf);
                vo.setMaterialCode(materialHalf.getMaterialCode());
                vo.setMaterialName(materialHalf.getMaterialName());
                vo.setMaterialSpec(materialHalf.getMaterialSpec());
                vo.setMaterialRatio(materialHalf.getMaterialRatio());
                vo.setMaterialTypeName(materialHalf.getMaterialTypeName());
            }
        }
        return list;
    }


    /**
     * 新增BOM信息
     *
     * @param materialBomVo bom信息接受类
     * @return 成功1 失败0
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBom(MaterialBomVo materialBomVo) throws Exception{
        materialBomVo.setDeptId(SecurityUtils.getDeptId());
        materialBomVo.setBomCode(sysMidSplitServiceImpl.splitStr("bomCode"));
        materialBomVo.setCreateBy(SecurityUtils.getUsername());
        int ins = materialBomMapper.insertBom(materialBomVo);
        if(ins==0){
            throw new SQLException("抛出异常");
        }
        ins = addBomSharing(materialBomVo);
        return ins;
    }

    /**
     * 查询单个BOM信息
     *
     * @param bomId bomid
     * @return MaterialBomDto
     */
    @Override
    public MaterialBomDto getBomInfo(long bomId) {
        MaterialBomVo materialBomVo = new MaterialBomVo();
        materialBomVo.setBomId(bomId);
        //先查询所有
        List<MaterialBomDto> list = materialBomMapper.selectlBomList(materialBomVo);
        MaterialBomDto materialBomDto = list.get(0);
        int jk = materialBomDto.getBomType();
        //半成品
        if(jk==3){
            materialBomDto.setMaterialTypeName("半成品");
            MaterialHalfVo materialHalf = new MaterialHalfVo();
            MaterialHalfDto materialHalfDto = new MaterialHalfDto();
            materialHalf.setMaterialId(materialBomDto.getMaterialId());
            List<MaterialHalfDto> haList = materialHalfMapper.selectHalfList(materialHalf);
            materialHalfDto = haList.get(0);
            materialBomDto.setMaterialCode(materialHalfDto.getMaterialCode());
            materialBomDto.setMaterialName(materialHalfDto.getMaterialName());
            materialBomDto.setMaterialSpec(materialHalfDto.getMaterialSpec());
            materialBomDto.setMaterialTypeName(materialHalfDto.getMaterialTypeName());
        }else{
            //成品
            MaterialFinished materialFinished = new MaterialFinished();
            materialFinished.setMaterialId(materialBomDto.getMaterialId());
            materialFinished = materialFinishedMapper.selectFinishedByList(materialFinished);
            materialBomDto.setMaterialCode(materialFinished.getMaterialCode());
            materialBomDto.setMaterialName(materialFinished.getMaterialName());
            materialBomDto.setMaterialSpec(materialFinished.getMaterialSpec());
            materialBomDto.setMaterialTypeName(materialFinished.getMaterialTypeName());
        }

        List<MaterialBomDetail> list2 =  infoBomDetailSharing(bomId);
        materialBomDto.setBomDetailCode(list2);
        return materialBomDto;
    }

    /**
     * 修改BOM信息
     *
     * @param materialBomVo bom接受类
     * @return 1 成功 0 失败
     */
    @Override
    public int updateMaterialBomEdit(MaterialBomVo materialBomVo) throws Exception{
        String[] bomIdS = String.valueOf(materialBomVo.getBomId()).split(",");
        int ins = materialBomDetailMapper.deleteMaterialBom(bomIdS);
        if(ins==0){
            throw new SQLException("抛出异常");
        }
        int in = addBomSharing(materialBomVo);
        if(in==0){
            throw new SQLException("抛出异常");
        }
        return in;
    }

    /**
     * 删除BOM信息
     *
     * @param bomId bomId
     * @return 1 成功 0 失败
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteMaterialBomById(String bomId) throws Exception {
        String[] bomIdS = bomId.split(",");
        int in = materialBomMapper.deleteMaterialBomById(bomIdS);
        if(in>0){
            int jl = materialBomDetailMapper.deleteMaterialBom(bomIdS);
            if(jl==0){
                throw new SQLException("抛出异常");
            }
        }else{
            throw new SQLException("抛出异常");
        }
        return in;
    }

    /**
     * 查询BOM明细 分页(材料bom)
     *
     * @param bomId id
     * @return List<MaterialBomDetail>
     */
    @Override
    public List<MaterialBomDetail> selectlBomDetailList(long bomId) {
        List<MaterialBomDetail> list = infoBomDetailSharing(bomId);
        List<MaterialBomDetail> list2 = new ArrayList<>();
        for (MaterialBomDetail bom:
        list) {
            if(!bom.getBomDetailType().equals("2")){
                list2.add(bom);
            }
        }
        return list2;
    }

    /**
     * 查询BOM明细 分页(辅料bom)
     *
     * @param bomId id
     * @return List<MaterialBomDetail>
     */
    @Override
    public List<MaterialBomDetail> selectlBomDetailListAll(long bomId) {
        List<MaterialBomDetail> list = infoBomDetailSharing(bomId);
        List<MaterialBomDetail> list2 = new ArrayList<>();
        for (MaterialBomDetail bom:
                list) {
            if(bom.getBomDetailType().equals("2")){
                list2.add(bom);
            }
        }
        return list2;
    }

    /**
     * 查询BOM明细 不分页(库存量)
     *
     * @param bomId id
     * @return List<MaterialBomDetail>
     */
    @Override
    public List<MaterialBomDetail> selectlBomDetailListInventory(long bomId) {
        List<MaterialBomDetail> list = infoBomDetailSharing(bomId);
        for (MaterialBomDetail de:
        list) {
            de.setInventory(1);
        }
        return list;
    }


    /**
     * 获取BOM信息(根据物料编码)
     */
    @Override
    public List<MaterialBomDetailApi> selectBomDetailComposition(String code) {
        List<MaterialBomDetailApi> list = materialBomDetailMapper.selectBomDetailList(code);
        //查询出物料名称以及物料规格
        for (MaterialBomDetailApi de: list) {
            String type = de.getBomDetailType();
            long materialId = de.getBomMaterialId();
            switch (type) {
                //原料
                case "1":
                    MaterialAwmateriaDto dto = materialAwmateriaMapper.selectAwmateriaById(materialId);
                    de.setMaterialName(dto.getMaterialName());
                    de.setMaterialSpec(dto.getMaterialSpec());
                    break;
                case "3":
                    MaterialHalf Half = new MaterialHalf();
                    Half.setMaterialId(materialId);
                    MaterialHalf Half1 = materialHalfMapper.selectHalfByList(Half);
                    de.setMaterialName(Half1.getMaterialName());
                    de.setMaterialSpec(Half1.getMaterialSpec());
                    break;
                case "2":
                    MaterialAccessories accessories = materialAccessoriesMapper.selectAccessoriesOneById(materialId);
                    de.setMaterialName(accessories.getMaterialName());
                    de.setMaterialSpec(accessories.getMaterialSpec());
                default:
                    break;
            }
        }
/*        for (MaterialBomDetail de: list) {
            //查询该物料是否符合占比所需要的重量
            //查询是否存在替代料 替代料 1 开 2 关
            int behalfOf = de.getBomDetailDosage();
            if(behalfOf == 1){
                //存在替代料 查询
                List<MaterialBomBehalf> behalfList = materialBomBehalfMapper.selectBomBehalfList(de.getBomDetailId());
            }
        }*/
        return list;
    }

    /**
     * 根据编码获取半成品bom信息(fegin调用)
     * @param materialCode
     * @return
     */
    @Override
    public List<MaterialBomDetail> getHalfData(String materialCode) {
        Long bomId = materialBomMapper.getBomIdByMaterialCode(materialCode);
        //根据bomid获取对应的物料
        return materialBomDetailMapper.selectlBomDetailList(bomId);
    }

    /**
     * 共用BOM信息新增
     *
     * @param materialBomVo bom接受类
     * @return 1 成功 0 失败
     */
    @Transactional(rollbackFor = Exception.class)
    public int addBomSharing (MaterialBomVo materialBomVo) throws Exception{
        List<MaterialBomDetail> list= JSONArray.parseArray(materialBomVo.getBomDetailCode().toJSONString(), MaterialBomDetail.class);
        List<MaterialBomDetail> list2= JSONArray.parseArray(materialBomVo.getBomDetailCode2().toJSONString(), MaterialBomDetail.class);
        long bomId = materialBomVo.getBomId();
        list.addAll(list2);
        int ins = 0;
        for (MaterialBomDetail materialBomDetail:
                list) {
            materialBomDetail.setBomId(bomId);
            ins = materialBomDetailMapper.insertBomDetailBy(materialBomDetail);
            if(ins==0){
                throw new SQLException("抛出异常");
            }
            List<MaterialBomBehalf> behalfList = materialBomDetail.getChild();
            if(behalfList.size()>0){
                for (MaterialBomBehalf be:
                behalfList) {
                    be.setBomDetailId(materialBomDetail.getBomDetailId());
                }
                ins = materialBomBehalfMapper.insertBomBehalf(behalfList);
            }
        }
        return ins;
    }


    /**
     * 共用BOM信息查询
     *
     * @param bomId bomId
     * @return List<MaterialBomDetail>
     */
    public List<MaterialBomDetail> infoBomDetailSharing (long bomId) {
        List<SysDictData> dictList= DictUtils.getDictCache("sys_material_unit");
        Map<String, String> actualMap = dictList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        List<MaterialBomDetail> list = materialBomDetailMapper.selectlBomDetailList(bomId);
        for (MaterialBomDetail bomDetail :
                list) {
            int ui = Integer.parseInt(bomDetail.getBomDetailType());
            long maId = bomDetail.getBomMaterialId();
            switch (ui) {
                //代表原料
                case 1:
                    MaterialAwmateriaDto materialAwmateriaDto = materialAwmateriaMapper.selectAwmateriaById(maId);
                    bomDetail.setMaterialCode(materialAwmateriaDto.getMaterialCode());
                    bomDetail.setMaterialName(materialAwmateriaDto.getMaterialName());
                    bomDetail.setMaterialSpec(materialAwmateriaDto.getMaterialSpec());
                    bomDetail.setMaterialUnit(materialAwmateriaDto.getMaterialUnit());
                    bomDetail.setMaterialUnitDict(actualMap.get(materialAwmateriaDto.getMaterialUnit()));
                    bomDetail.setMaterialType("1");
                    bomDetail.setMaterialTypeDict("原料");
                    bomDetail.setMaterialCategory(materialAwmateriaDto.getMaterialType());
                    bomDetail.setMaterialCategoryDict(materialAwmateriaDto.getMaterialCategory());
                    break;
                //代表半成品
                case 3:
                    MaterialHalfVo materiaHalf = new MaterialHalfVo();
                    MaterialHalfDto materialHalfDto = new MaterialHalfDto();
                    materiaHalf.setMaterialId(maId);
                    List<MaterialHalfDto> haList = materialHalfMapper.selectHalfList(materiaHalf);
                    materialHalfDto = haList.get(0);
                    bomDetail.setMaterialCode(materialHalfDto.getMaterialCode());
                    bomDetail.setMaterialName(materialHalfDto.getMaterialName());
                    bomDetail.setMaterialSpec(materialHalfDto.getMaterialSpec());
                    bomDetail.setMaterialUnit(materialHalfDto.getMaterialUnit());
                    bomDetail.setMaterialUnitDict(actualMap.get(materialHalfDto.getMaterialUnit()));
                    bomDetail.setMaterialType("3");
                    bomDetail.setMaterialTypeDict("半成品");
                    bomDetail.setMaterialCategory(materialHalfDto.getMaterialType());
                    bomDetail.setMaterialCategoryDict(materialHalfDto.getMaterialCategory());
                    break;
                //代表辅料
                case 2:
                    MaterialAccessoriesVo materialAccessories = new MaterialAccessoriesVo();
                    materialAccessories.setMaterialId(maId);
                    List<MaterialAwmateriaDto> list3 = materialAccessoriesMapper.selectAccessoriesList(materialAccessories);
                    MaterialAwmateriaDto material = new MaterialAwmateriaDto();
                    material = list3.get(0);
                    bomDetail.setMaterialCode(material.getMaterialCode());
                    bomDetail.setMaterialName(material.getMaterialName());
                    bomDetail.setMaterialSpec(material.getMaterialSpec());
                    bomDetail.setMaterialUnit(material.getMaterialUnit());
                    bomDetail.setMaterialUnitDict(actualMap.get(material.getMaterialUnit()));
                    break;
                default:
                    break;
            }
            //判断是否存在替代料
            int ti = bomDetail.getBomDetailAlternative();
            //代表存在替代料
            if(ti==1){
                List<MaterialBomBehalf>  list2 = materialBomBehalfMapper.selectBomBehalfList(bomDetail.getBomDetailId());
                for (MaterialBomBehalf behalf:
                        list2) {
                    long maiId = behalf.getBomMaterialId();
                    //代表原料
                    if(behalf.getBomBehalfType()==1){
                        MaterialAwmateriaDto materialAwmateriaDto = materialAwmateriaMapper.selectAwmateriaById(maiId);
                        behalf.setMaterialCode(materialAwmateriaDto.getMaterialCode());
                        behalf.setMaterialName(materialAwmateriaDto.getMaterialName());
                        behalf.setMaterialSpec(materialAwmateriaDto.getMaterialSpec());
                        behalf.setMaterialUnit(materialAwmateriaDto.getMaterialUnit());
                        behalf.setMaterialUnitDict(actualMap.get(materialAwmateriaDto.getMaterialUnit()));
                    }else{//代表半成品
                        MaterialHalfVo materialHalf = new MaterialHalfVo();
                        MaterialHalfDto materialHalfDto = new MaterialHalfDto();
                        materialHalf.setMaterialId(maiId);
                        List<MaterialHalfDto> haList = materialHalfMapper.selectHalfList(materialHalf);
                        materialHalfDto = haList.get(0);
                        behalf.setMaterialCode(materialHalfDto.getMaterialCode());
                        behalf.setMaterialName(materialHalfDto.getMaterialName());
                        behalf.setMaterialSpec(materialHalfDto.getMaterialSpec());
                        behalf.setMaterialUnit(materialHalfDto.getMaterialUnit());
                        behalf.setMaterialUnitDict(actualMap.get(materialHalfDto.getMaterialUnit()));
                    }
                }
                bomDetail.setChild(list2);
            }

        }
        return list;
    }
}
